<template>
	<div class="system-role-dialog-container">
		<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="769px">
			<el-form ref="roleDialogFormRef" :model="state.ruleForm" :rules="rules" size="default" label-width="90px">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="角色名称" prop="roleName">
							<el-input v-model="state.ruleForm.roleName" placeholder="请输入角色名称" clearable
								:disabled="formReadonly"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="角色标识" prop="roleSign">
							<el-input v-model="state.ruleForm.roleSign" placeholder="请输入角色标识" clearable
								:disabled="formReadonly"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="排序" prop="sort">
							<el-input-number v-model="state.ruleForm.sort" :min="0" :max="999" controls-position="right"
								placeholder="请输入排序" class="w100" :disabled="formReadonly" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="角色状态" prop="active">
							<el-switch v-model="state.ruleForm.active" :active-value="1" :inactive-value="0" inline-prompt
								active-text="启用" inactive-text="禁用" :disabled="formReadonly">
							</el-switch>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="角色描述" prop="remark">
							<el-input v-model="state.ruleForm.remark" :disabled="formReadonly" type="textarea" placeholder="请输入角色描述"
								maxlength="150"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20" v-show="formReadonly">
						<el-form-item label="菜单权限">
							<el-tree ref="menuTreeRef" node-key="id" :data="state.menuData" :props="state.menuProps" show-checkbox
								class="menu-data-tree" />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit(roleDialogFormRef)" size="default">
						{{ state.dialog.submitTxt }}
					</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="systemRoleDialog">
import { reactive, ref, nextTick, computed } from 'vue';
import type { FormInstance, FormRules } from 'element-plus';
import type { RoleType } from '/@/api/sys/types';
import { roleApi } from '/@/api/sys/role';
import { useMenuApi } from '/@/api/sys/menu';
import { ElMessage } from 'element-plus';
// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 定义变量内容
const roleDialogFormRef = ref();
const menuTreeRef = ref()
const state = reactive({
	ruleForm: {
		roleName: '', // 角色名称
		roleSign: '', // 角色标识
		sort: 0, // 排序
		active: 1, // 角色状态
		remark: '', // 角色描述
		menuIdList: [], // 菜单ids
	},
	menuData: [] as TreeType[],
	menuProps: {
		children: 'children',
		label: 'title',
		class: (data: any): string => {
			if (data.children && data.children.length > 0 && data.children[0].type === 'btn') {
				return 'is-penultimate'
			}
			return ""
		}
	},
	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitTxt: '',
	},
});
const backupFormData = JSON.parse(JSON.stringify(state.ruleForm));

const rules = reactive<FormRules>({
	roleName: [{ required: true, message: '不能为空', trigger: 'blur' }],
	roleSign: [{ required: true, message: '不能为空', trigger: 'blur' }],
});
// 打开弹窗
const openDialog = (type: string, row: RoleType) => {
	state.dialog.type = type;
	state.dialog.isShowDialog = true;
	if (row) {
		state.ruleForm = JSON.parse(JSON.stringify(row));
	}
	if (type === 'edit') {
		state.dialog.title = '修改角色';
		state.dialog.submitTxt = '修 改';
	} else if (type === 'add') {
		state.dialog.title = '新增角色';
		state.dialog.submitTxt = '新 增';
		nextTick(() => {
			state.ruleForm = backupFormData;
		});
	} else if (type === 'assign') {
		state.dialog.title = '分配权限';
		state.dialog.submitTxt = '分 配';
		roleApi().roleMenuList(row.id).then((res) => {
			state.ruleForm.menuIdList = (res.data || []).map((a: any) => a.menuId as number);
			nextTick(() => {
				menuTreeRef.value.setCheckedKeys(state.ruleForm.menuIdList)
			})
		})
	}
	getMenuData();
};
// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
};
// 取消
const onCancel = () => {
	closeDialog();
};
// 提交
const onSubmit = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	if (state.dialog.type === 'assign') {
		const checkedKeys = menuTreeRef.value.getCheckedKeys()
		const menuIds = checkedKeys.concat([])
		state.ruleForm.menuIdList = menuIds
		roleApi().assignMenus(state.ruleForm).then((res) => {
			closeDialog();
			ElMessage.success(res.msg || '分配成功');
			emit('refresh');
		})
		return;
	}
	formEl.validate((valid) => {
		if (valid) {
			if (state.dialog.type === 'add') {
				roleApi()
					.addRecord(state.ruleForm)
					.then((res) => {
						closeDialog();
						ElMessage.success(res.msg || '新增成功');
						emit('refresh');
					});
			} else if (state.dialog.type === 'edit') {
				roleApi()
					.updateRecord(state.ruleForm)
					.then((res) => {
						closeDialog();
						ElMessage.success(res.msg || '修改成功');
						emit('refresh');
					});
			}
		}
	});
};
// 获取菜单结构数据
const getMenuData = () => {
	useMenuApi().getMenu().then((res) => {
		state.menuData = res.data;
	})
};
const formReadonly = computed(() => {
	return state.dialog.type !== 'add' && state.dialog.type !== 'edit'
})
// 暴露变量
defineExpose({
	openDialog,
});
</script>

<style scoped lang="scss">
.system-role-dialog-container {
	.menu-data-tree {
		width: 100%;
		border: 1px solid var(--el-border-color);
		border-radius: var(--el-input-border-radius, var(--el-border-radius-base));
		padding: 5px;
	}
}
</style>

<style>
.is-penultimate>.el-tree-node__content {
	color: #626aef;
}

.el-tree-node.is-expanded.is-penultimate>.el-tree-node__children {
	display: flex;
	flex-direction: row;
}

.is-penultimate>.el-tree-node__children>div {
	width: 25%;
}
</style>